<template>
  <div class="app-container calendar-list-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input clearable class="filter-item" style="width: 200px;" placeholder="请输入平台编号" v-model="listQuery.platformId"></el-input>
      <el-input clearable class="filter-item" style="width: 200px;" placeholder="请输入商户号" v-model="listQuery.merchantId"></el-input>
      <el-input clearable class="filter-item" style="width: 200px;" placeholder="请输入商品编号" v-model="listQuery.goodsId"></el-input>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <!-- <el-button class="filter-item" type="primary" @click="handleCreate" icon="el-icon-plus">添加</el-button> -->
      <input type="file" @change="importFile(this)" id="imFile" style="display: none"
            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"/>
          <a id="downlink"></a>
      <el-button class="filter-item" type="primary" @click="handleImport()">导入</el-button>
      <el-button class="filter-item" type="primary" @click="handleCreateQr()">批量生成二维码</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table :row-key="getRowKeys" ref="multipleTable" @selection-change="handleSelectionChange" size="small" :data="list" v-loading="listLoading" element-loading-text="正在查询中。。。" border fit highlight-current-row>
      <el-table-column type="selection" width="35">
      </el-table-column>
      <el-table-column align="center" label="平台编号" width="150" prop="platformId">
      </el-table-column>
      <el-table-column align="center" label="商户号" width="150" prop="merchantId">
      </el-table-column>
      <el-table-column align="center" label="商品编号" width="120" prop="goodsId">
      </el-table-column>
      <!-- <el-table-column align="center" label="商品名称" prop="goodsName">
      </el-table-column> -->
      <el-table-column align="center" label="商品价格" width="90" prop="goodsPrice">
      </el-table-column>
      <!-- <el-table-column align="center" property="goodsPic" width="150" label="商品图片">
        <template slot-scope="scope">
          <img :src="scope.row.goodsPic" width="40"/>
        </template>
      </el-table-column> -->
      <el-table-column align="center" prop="attribute" width="90" label="商品属性">
      </el-table-column>
      <el-table-column align="center" width="100" label="入库日期">
        <template slot-scope="scope">
          <span>{{scope.row.storageDate | formatDate1}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="shelfDate" width="100" label="上架日期">
        <template slot-scope="scope">
          <span>{{scope.row.shelfDate | formatDate1}}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column align="center" prop="offDate" label="取关日期">
      </el-table-column> -->
      <el-table-column align="center" prop="firstScanDate" width="100" label="首次扫描日期">
        <template slot-scope="scope">
          <span>{{scope.row.firstScanDate | formatDate1}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="scanCount" width="100" label="扫描次数">
      </el-table-column>
      <el-table-column align="center" prop="firstPayDate" width="100" label="首次付费日期">
      </el-table-column>
      <el-table-column align="center" prop="payCount" width="100" label="付费次数">
      </el-table-column>
      <el-table-column align="center" prop="attribute" width="100" label="上次付费日期">
      </el-table-column>
      <el-table-column align="center" prop="operatorId" width="100" label="运营人员id">
      </el-table-column>
      <!-- <el-table-column align="center" prop="pwdStartBit" width="100" label="密码起始位">
      </el-table-column> -->
      <!-- <el-table-column align="center" prop="pwdLibrary" label="密码库">
      </el-table-column> -->

      <el-table-column align="center" label="操作" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button type="danger" size="mini"  @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page"
        :page-sizes="[10,20,30,50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <!-- 添加对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
        <el-form :rules="rules" ref="form" :model="form" status-icon label-position="left" label-width="100px" style='width: 400px; margin-left:50px;'>
            <el-form-item label="商品价格" prop="goodsPrice">
              <el-input v-model="form.goodsPrice" clearable=""></el-input>
            </el-form-item>
            <el-form-item label="商品属性" prop="attribute">
              <el-input v-model="form.attribute" clearable=""></el-input>
            </el-form-item>           
            <el-form-item label="商品图片" prop="goodsPic">
              <div  @click="upGoodsImg">
                <img v-if="form.goodsPic" :src="form.goodsPic">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </div>
              <input type="file" name="file" id="upload_img" @change="uploadGoodsImg" accept="image/png,image/gif" style="display: none">
            </el-form-item>      
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button v-if="dialogStatus == 'create'" type="primary" @click="createData('form')">确定</el-button>
            <el-button v-if="dialogStatus == 'update'" type="primary" @click="updateData('form')">确定</el-button>
        </div>
    </el-dialog> 

    <el-tooltip placement="top" content="返回顶部">
      <back-to-top :visibilityHeight="100" ></back-to-top>
    </el-tooltip>



  </div>
</template>

<style>
  .table-expand {
    font-size: 0;
  }
  .table-expand label {
    width: 100px;
    color: #99a9bf;
  }
  .table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
  }
  .gallery {
    width: 80px;
    margin-right: 10px;
  }
</style>

<script>
import { allGoods, deleteObj, importObj } from '@/api/qr/goods/index'
import BackToTop from '@/components/BackToTop'
import { mapGetters } from 'vuex'
import { formatDate } from '@/utils/index'
import { uploadImg } from '@/api/cms/society/index'
var XLSX = require('xlsx')
export default {
  name: 'GoodsList',
  components: { BackToTop },
  data() {
    return {
      list: [],
      total: 0,
      listLoading: false,
      listQuery: {
        page: 1,
        limit: 20,
        goodsId: undefined,
        platformId: undefined,
        order: 'desc',
        merchantId: ''
      },
      goodsIdArr: '',
      imFile: '',
      excelData: [],
      goodsDetail: '',
      dialogFormVisible: false,
      downloadLoading: false,
      dialogStatus: '',
      textMap: {
        create: '新增',
        update: '修改'
      },
      form: {
        goodsPrice: '',
        attribute: '',
        goodsPic: ''
      },
      rules: {

      }
    }
  },
  computed: {
    ...mapGetters([
      'elements',
      'name'
    ])
  },
  mounted() {
    this.imFile = document.getElementById('imFile')
  },
  filters: {
    formatDate1(time) {
      var date = new Date(time)
      return formatDate(date, 'yyyy-MM-dd')
    }
  },
  created() {
    this.getList()
  },
  methods: {
    importFile: function() { // 导入excel
      this.listLoading = true
      const obj = this.imFile
      if (!obj.files) {
        this.listLoading = false
        return
      }
      var f = obj.files[0]
      var reader = new FileReader()
      const $t = this
      reader.onload = function(e) {
        var data = e.target.result
        if ($t.rABS) {
          $t.wb = XLSX.read(btoa(this.fixdata(data)), { // 手动转化
            type: 'base64'
          })
        } else {
          $t.wb = XLSX.read(data, {
            type: 'binary'
          })
        }
        const json = XLSX.utils.sheet_to_json($t.wb.Sheets[$t.wb.SheetNames[0]])
        console.log(typeof json)
        $t.dealFile($t.analyzeData(json)) // analyzeData: 解析导入数据
      }
      if (this.rABS) {
        reader.readAsArrayBuffer(f)
      } else {
        reader.readAsBinaryString(f)
      }
    },
    analyzeData: function(data) { // 此处可以解析导入数据
      return data
    },
    dealFile: function(data) { // 处理导入的数据
      console.log(data)
      this.imFile.value = ''
      if (data.length <= 0) {
        this.errorDialog = true
        this.errorMsg = '请导入正确信息'
      } else {
        this.excelData = data
        this.importExcelData(data)
      }
    },
    s2ab: function(s) { // 字符串转字符流
      var buf = new ArrayBuffer(s.length)
      var view = new Uint8Array(buf)
      for (var i = 0; i !== s.length; ++i) {
        view[i] = s.charCodeAt(i) & 0xFF
      }
      return buf
    },
    getCharCol: function(n) { // 将指定的自然数转换为26进制表示。映射关系：[0-25] -> [A-Z]。
      let s = ''
      let m = 0
      while (n > 0) {
        m = n % 26 + 1
        s = String.fromCharCode(m + 64) + s
        n = (n - m) / 26
      }
      return s
    },
    fixdata: function(data) { // 文件流转BinaryString
      var o = ''
      var l = 0
      var w = 10240
      for (; l < data.byteLength / w; ++l) {
        o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)))
      }
      o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)))
      return o
    },
    getList() {
      this.listLoading = true
      allGoods(this.listQuery).then(response => {
        this.list = response.data.rows
        this.total = response.data.total
        this.listLoading = false
      }).catch(() => {
        this.list = []
        this.total = 0
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    // 导入excel数据
    importExcelData(rows) {
      var str = {}
      str.rows = rows
      str.platformId = this.platformId
      importObj(str).then(response => {
        this.getList()
      })
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    handleUpdate(row) {
      this.form = row
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
    },
    showDetail(detail) {
      this.goodsDetail = detail
      this.detailDialogVisible = true
    },
    handleDelete(row) {
      deleteObj(row).then(response => {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        this.getList()
      })
    },
    handleImport: function() {
      this.imFile.click()
    },
    handleSelectionChange(rows) {
      var msgNoSt1r = ''
      if (rows) {
        rows.forEach(row => {
          if (row) {
            if (msgNoSt1r === '') {
              msgNoSt1r = row.goodsId
            } else {
              msgNoSt1r = msgNoSt1r + ',' + row.goodsId
            }
          }
        })
      }
      this.goodsIdArr = msgNoSt1r
      console.log(this.goodsIdArr)
    },
    handleCreateQr() {
      if (this.goodsIdArr === '') {
        alert('没有选中项')
        return
      }
      // alert('绑定商户的商品才能生成二维码')
      var str = {}
      str.idStr = this.goodsIdArr.toString()

      this.axios.post('api/adminthymeleaf/qrGoodsInfos/downloadZipQr', str, {
        responseType: 'blob'
      }).then(function(res) {
        console.log(res.data)
        const fileDownload = require('js-file-download')
        const fileName = res.headers['content-disposition'].split(';')[1].split('=')[1]
        console.log(fileName[1].split('=')[1])

        // var blob = new Blob([res.data], { type: 'application/octet-stream' })

        fileDownload(res.data, 'GoodsQr.zip')
        // 控制台打印请求成功时返回的数据
        // bind(this)可以不用
      }).catch(function(err) {
        if (err.response) {
          console.log(err.response)
          // 控制台打印错误返回的内容
        }
        // bind(this)可以不用
      })

      /* createQr(str).then(res => {
        console.log(res)
        let fileDownload = require('js-file-download')
        fileDownload(res,'GoodsQr.zip')
      }) */
    },
    upGoodsImg: function() {
      document.getElementById('upload_img').click()
    },
    uploadGoodsImg(event) {
      if (event.target.files.length > 0) {
        this.file = event.target.files[0] // 提交的图片
        console.log(this.file)
        const param = new FormData() // 创建form对象
        param.append('file', this.file)
        uploadImg(param).then(response => {
          if (response.success) {
            this.form.goodsPic = response.data.filePath
          }
        })
      }
    },
    resetForm() {
      this.form = {
        goodsPrice: '',
        attribute: '',
        goodsPic: ''
      }
    }
  }
}
</script>
